import sys
import os
sys.path.append(os.getcwd())
from impl import run
import subprocess
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QTextBrowser, QMessageBox, QDialog, QVBoxLayout, QCheckBox
from MainUi import Ui_auto_frame
from impl.display import Display
import ctypes
# 主窗口继承QTMain子类


class Mainwindows (QMainWindow, Ui_auto_frame):
    def __init__(self):
       # 初始化父类
        super().__init__()
        # 加载UI代码
        self.setupUi(self)
      # 按钮绑定逻辑
        self.startButton.clicked.connect(self.startAction)
        self.configButton.clicked.connect(self.ConfigAction)
        self.finish.clicked.connect(self.checkBoxfinish)
        self.unfinish.clicked.connect(self.checkBoxUnfinish)
        # 将信号触发链接到displayInfo函数
        # 此处是开始位置管理对象
        self.display = Display()
        self.display.displaySignal.connect(self.displayInfo)
        self.mainlogic = run.MainLogic(self.display)

    def checkBoxUnfinish(self):
        dialog = QDialog(self)
        dialog.setWindowTitle("New Window")

        # 创建一个新窗口的布局
        layout = QVBoxLayout(dialog)

        # 创建取消按钮并添加到布局中
        cancel_button = QPushButton("取消", dialog)
        layout.addWidget(cancel_button)

        # 创建确认按钮并添加到布局中
        confirm_button_1 = QPushButton("重新运行全部", dialog)
        layout.addWidget(confirm_button_1)

        confirm_button_2 = QPushButton("仅打开选中", dialog)
        layout.addWidget(confirm_button_2)

        # 连接取消按钮和确认按钮的点击事件到槽函数
        cancel_button.clicked.connect(dialog.reject)
        confirm_button_1.clicked.connect(self.rerun)
        confirm_button_2.clicked.connect(self.OpenConfigUnFinish)

        self.selectedItemsUnFinish = []  # 存储选中的复选框
       # 判断是否有未完成
        unfinishWord = self.mainlogic.readUnfinishWord()
        if (not unfinishWord):
            self.showInfo("没有未完成")
            return

        for word in unfinishWord:
            # 创建复选框并添加到布局中
            checkbox = QCheckBox(word, dialog)
            layout.addWidget(checkbox)
            self.selectedItemsUnFinish.append(checkbox)

        # 显示新窗口作为对话框
        dialog.exec()

    def checkBoxfinish(self):
        dialog = QDialog(self)
        dialog.setWindowTitle("New Window")

        # 创建一个新窗口的布局
        layout = QVBoxLayout(dialog)

        # 创建取消按钮并添加到布局中
        cancel_button = QPushButton("取消", dialog)
        layout.addWidget(cancel_button)

        confirm_button = QPushButton("打开选中", dialog)
        layout.addWidget(confirm_button)

        # 连接取消按钮和确认按钮的点击事件到槽函数
        cancel_button.clicked.connect(dialog.reject)
        confirm_button.clicked.connect(self.OpenConfigFinish)

        self.selectedItemsFinish = []  # 存储选中的复选框
       # 判断是否有未完成
        finishWord = self.mainlogic.readfinishWord()
        if (not finishWord):
            self.showInfo("没有已完成")
            return

        for word in finishWord:
            # 创建复选框并添加到布局和数组中
            checkbox = QCheckBox(word, dialog)
            layout.addWidget(checkbox)
            self.selectedItemsFinish.append(checkbox)

        # 显示新窗口作为对话框
        dialog.exec()

    def rerun(self):
        self.mainlogic.reRun()

    def run(self):
        self.mainlogic.run()

    def OpenConfigFinish(self):
        # self.showInfo('在运行浏览器时gui无法操作')

        # 遍历复选框取出对应选中的word
        for checkBox in self.selectedItemsFinish:
            if (checkBox.isChecked()):
                self.mainlogic.openConfig(checkBox.text())

    def OpenConfigUnFinish(self):

        # 遍历复选框取出对应选中的word
        for checkBox in self.selectedItemsUnFinish:
            if (checkBox.isChecked()):
                self.mainlogic.openConfig(checkBox.text())

    # 显示到窗口
    def displayInfo(self, text):

        self.textBrowser = self.findChild(QTextBrowser, 'text')
        self.textBrowser.append(str(text))

     # 弹出提示框
    def showInfo(self, text):
        QMessageBox.information(self, '提示信息', str(text))


# 逻辑

    def startAction(self):
        self.displayInfo("start")
        self.mainlogic.run()
        print('start')

    def ConfigAction(self):
        self.displayInfo("action")

        file_path = os.getcwd() + "\\lib\\config.txt"  # 相对路径

        try:
            subprocess.run(["start", str(file_path)], shell=True)
        except FileNotFoundError:
            self.displayInfo("文件未找到")
        except subprocess.SubprocessError:
            self.displayInfo("无法打开文件")
        print('action')


def run_as_admin():
    try:
        # 检查是否以管理员权限运行
        if not ctypes.windll.shell32.IsUserAnAdmin():
            # 重新启动脚本以获取管理员权限
            ctypes.windll.shell32.ShellExecuteW(
                None, "runas", sys.executable, __file__, None, 1)
            sys.exit()
    except Exception as e:
        print("无法获取管理员权限:", e)
        sys.exit(1)


if __name__ == "__main__":
    #run_as_admin()
    app = QApplication(sys.argv)

    # 主窗口
    win = Mainwindows()

    win.show()
    sys.exit(app.exec_())
